<template>
  <div class="admin-container">
    <el-container>
      <el-aside width="200px">
        <el-menu
          :default-active="activeMenu"
          class="admin-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="products">
            <el-icon><goods /></el-icon>
            <span>商品管理</span>
          </el-menu-item>
          <el-menu-item index="records">
            <el-icon><calendar /></el-icon>
            <span>早睡记录管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <div v-if="activeMenu === 'products'">
          <div class="header-actions">
            <h2>商品管理</h2>
            <el-button type="primary" @click="showAddProductDialog">新增商品</el-button>
          </div>
          <el-table :data="products" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="商品名称"/>
            <el-table-column prop="points" label="价格"/>
            <el-table-column prop="stock" label="库存"/>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <span>{{ formatStatus(scope.row.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="图片" width="120">
              <template #default="scope">
                <el-image 
                  style="width: 100px; height: 100px" 
                  :src="scope.row.url" 
                  :preview-src-list="[scope.row.url]"
                  fit="cover"
                  lazy
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="editProduct(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 商品分页器 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="productPagination.current"
              v-model:page-size="productPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productTotal"
              @size-change="handleProductSizeChange"
              @current-change="handleProductCurrentChange"
              background
            />
          </div>

          <el-dialog
            v-model="productDialogVisible"
            :title="isEditingProduct ? '编辑商品' : '新增商品'"
            width="500px"
          >
            <el-form :model="productForm" label-width="100px">
              <el-form-item label="商品名称">
                <el-input v-model="productForm.name" placeholder="请输入商品名称" />
              </el-form-item>
              <el-form-item label="商品图片">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload" 
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload" 
                >
                  <img v-if="productForm.url" :src="productForm.url" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number v-model="productForm.points" :min="0" />
              </el-form-item>
              <el-form-item label="库存">
                <el-input-number v-model="productForm.stock" :min="0" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="productForm.status" placeholder="请选择状态">
                  <el-option label="可用" value="AVAILABLE"></el-option>
                  <el-option label="不可用" value="UNAVAILABLE"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="productDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="isEditingProduct ? updateProduct() : saveProduct()">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        <div v-else-if="activeMenu === 'records'">
          <div class="header-actions">
            <h2>早睡记录管理</h2>
            <el-button type="primary" @click="showAddRecordDialog">新增记录</el-button>
          </div>
          <el-table :data="sleepRecords" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="userId" label="用户" width="120">
              <template #default="scope">
                <span>{{ getUserNickname(scope.row.userId) }}</span>
              </template>
            </el-table-column>
            <!-- 修改记录表单中的用户ID输入框为选择器 -->
            <el-form-item label="用户">
              <el-select v-model="recordForm.userId" placeholder="请选择用户" filterable>
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.nickname"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
            <el-table-column prop="actualTime" label="睡眠时间" />
            <el-table-column prop="targetTime" label="目标时间" />
            <el-table-column prop="pointsEarned" label="获得积分" />
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <span>{{ formatStatusForRecord(scope.row.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="viewRecord(scope.row)">查看</el-button>
                <el-button size="small" type="danger" @click="deleteRecord(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 早睡记录分页器 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="recordPagination.current"
              v-model:page-size="recordPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordTotal"
              @size-change="handleRecordSizeChange"
              @current-change="handleRecordCurrentChange"
              background
            />
          </div>

          <el-dialog
            v-model="recordDialogVisible"
            :title="isEditingRecord ? '编辑记录' : '新增记录'"
            width="500px"
          >
            <el-form :model="recordForm" label-width="100px">
              <el-form-item label="用户">
                <el-select v-model="recordForm.userId" placeholder="请选择用户" filterable :disabled="isEditingRecord">
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.nickname"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="睡眠时间">
                <el-date-picker :disabled="isEditingRecord"
                  v-model="recordForm.actualTime"
                  type="datetime"
                  placeholder="选择睡眠时间"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="recordForm.status" placeholder="请选择状态" :disabled="isEditingRecord">
                  <el-option label="已完成" value="success" />
                  <el-option label="未完成" value="fail" />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="recordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveRecord">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import { Goods, Calendar, Plus, Picture as IconPicture } from '@element-plus/icons-vue' // 引入 Picture 图标
import {useApi} from "@/api/product";
import {ElMessage} from "element-plus";
import {useUserApi} from "@/api/user";

const activeMenu = ref('products')
const products = ref([])
const sleepRecords = ref([])
const productTotal = ref(0)
const recordTotal = ref(0)

// 分页相关
const productPagination = ref({
  current: 1,
  size: 10
})

const recordPagination = ref({
  current: 1,
  size: 10
})

// 商品相关
const productDialogVisible = ref(false)
const isEditingProduct = ref(false)
const productForm = ref({
  name: '',
  url: '',
  points: 0,
  stock: 0,
  status: 'AVAILABLE'
})

// 记录相关
const recordDialogVisible = ref(false)
const isEditingRecord = ref(false)
const recordForm = ref({
  userId: '',
  actualTime: '',
  status: ''
})

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'products') {
    getProducts()
  } else if (index === 'records') {
    getSleepRecords()
  }
}

const showAddProductDialog = () => {
  isEditingProduct.value = false
  productForm.value = {
    name: '',
    url: '',
    points: 0,
    stock: 0,
    status: 'AVAILABLE'
  }
  productDialogVisible.value = true
}

onMounted(() => {
  getProducts()
})

// 查询商品列表（带分页）
const getProducts = async () => {
  try {
    const params = {
      pageNum: productPagination.value.current,
      pageSize: productPagination.value.size
    }
    const res = await useApi.adminProductsGetAll(params)
    if (res.code === 200) {
      products.value = res.data.records
      productTotal.value = res.data.total
    } else {
      ElMessage.error('获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表出错:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 查询早睡记录列表（带分页）
const getSleepRecords = async () => {
  try {
    const params = {
      pageNum: recordPagination.value.current,
      pageSize: recordPagination.value.size
    }
    // 假设有一个获取早睡记录的API
    const res = await useApi.getCheckInRecord(params)
    
    if (res.code === 200) {
      sleepRecords.value = res.data.records
      recordTotal.value = res.data.total
    } else {
      ElMessage.error('获取早睡记录失败')
    }
  } catch (error) {
    console.error('获取早睡记录出错:', error)
    ElMessage.error('获取早睡记录失败')
  }
}

// 商品分页事件处理
const handleProductSizeChange = (size) => {
  productPagination.value.size = size
  getProducts()
}

const handleProductCurrentChange = (current) => {
  productPagination.value.current = current
  getProducts()
}

// 早睡记录分页事件处理
const handleRecordSizeChange = (size) => {
  recordPagination.value.size = size
  getSleepRecords()
}

const handleRecordCurrentChange = (current) => {
  recordPagination.value.current = current
  getSleepRecords()
}

const editProduct = (product) => {
  isEditingProduct.value = true
  productForm.value = { ...product }
  productDialogVisible.value = true
}

const deleteProduct = async (product) => {
  const res = await useApi.adminProductsDelete(product.id);
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getProducts() // 刷新列表
  } else {
    ElMessage.error('删除失败')
  }
}

const handleAvatarSuccess = (response, uploadFile) => {
  // 假设后端返回的格式是 { code: 0, data: { url: '...' } } 或直接是 { url: '...' }
  productForm.value.url = response.data?.url || response.url || '' 
  // 可以添加 Element Plus 的 ElMessage 提示上传成功
}

// 可选：添加上传前校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是 JPG 或 PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const formatStatus = (status) => {
  if (status === 'AVAILABLE') {
    return '可用'
  }
  if (status === 'UNAVAILABLE') {
    return '不可用'
  }
  return status
}

const formatStatusForRecord = (status) => {
  if (status === 'success') {
    return '已完成'
  }
  if (status === 'fail') {
    return '未完成'
  }
  return status
}

const saveProduct = async () => {
  const res = await useApi.adminProductsAdd(productForm.value);
  if (res.code === 200) {
    ElMessage.success('保存成功')
    productDialogVisible.value = false
    getProducts() // 刷新列表
  } else {
    ElMessage.error('保存失败')
  }
}

const updateProduct = async () => {
  const res = await useApi.adminProductsUpdate(productForm.value);
  if (res.code === 200) {
    ElMessage.success('更新成功')
    productDialogVisible.value = false
    getProducts() // 刷新列表
  } else {
    ElMessage.error('更新失败')
  }
}

// 在script setup部分添加以下内容

// 用户列表数据
const userList = ref([])

// 获取用户列表
const getUserList = async () => {
  try {
    // 假设有一个获取用户列表的API
    // 请替换为实际的API调用
    const res = await useUserApi.getUserList()
    if (res.code === 200) {
      userList.value = res.data
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 在onMounted中添加获取用户列表
onMounted(() => {
  getProducts()
  getUserList() // 添加这一行
})

// 修改showAddRecordDialog函数
const showAddRecordDialog = () => {
  isEditingRecord.value = false
  recordForm.value = {
    userId: '', // 用户ID初始为空
    sleepTime: '',
    status: ''
  }
  recordDialogVisible.value = true
  // 确保有用户数据
  if (userList.value.length === 0) {
    getUserList()
  }
}

// 修改viewRecord函数
const viewRecord = (record) => {
  isEditingRecord.value = true
  recordForm.value = { ...record }
  recordDialogVisible.value = true
  // 确保有用户数据
  if (userList.value.length === 0) {
    getUserList()
  }
}

// 添加一个获取用户昵称的辅助函数
const getUserNickname = (userId) => {
  const user = userList.value.find(user => user.id === userId)
  return user ? user.nickname : userId
}

const deleteRecord = async (record) => {
  const res = await useApi.deleteRecord(record.id);
  if (res.code === 200) {
    ElMessage.success('删除成功')
    await getSleepRecords()
  } else {
    ElMessage.error('删除失败')
  }
}

const saveRecord = async () => {
  const res = await useApi.saveRecord(recordForm.value);
  if (res.code === 200) {
    ElMessage.success('保存成功')
    recordDialogVisible.value = false
    getSleepRecords()
  } else {
    ElMessage.error('保存失败')
  }
}
</script>

<style scoped>
.admin-container {
  height: 100vh;
}

.admin-menu {
  height: 100%;
  border-right: solid 1px #e6e6e6;
}

.el-aside {
  background-color: #fff;
}

.el-main {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions h2 {
  margin: 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>